import axios from 'axios'
import { Message } from '@ued_fpi/element-ui'
import { removeToken, redirectLogin } from '@utils/tools'
import configs from '@config'
const qs = require('qs')

// axios.defaults.withCredentials = true

/**
 * @description 基于axios的二次封装
 */

const Request = axios.create({
    baseURL: configs.urlDomain,
    timeout: 60 * 1000,
    validateStatus: status => {
        return (status >= 200 && status < 300) || status === 401
    },
    paramsSerializer: function (params) {
        return qs.stringify(params, { encode: true })
    },
})

Request.interceptors.request.use(
    config => {
        config.headers['Cache-Control'] = 'no-cache, no-store' // 清除缓存
        config.headers.Pragma = 'no-cache' // 清除缓存
        return config
    },
    error => {
        Promise.reject(error)
    }
)

Request.interceptors.response.use(
    response => {
        const { code, message } = response.data

        if ((response.status === 401 || code === 400) && configs.bspFlag) {
            removeToken()
            return redirectLogin()
        }

        if (code === '200' || code === 200) {
            return response.data
        } else if (code) {
            Message.info({ message: message || '数据异常，请稍后再试' })
            return Promise.reject(response.data)
        } else {
            return Promise.resolve(response.data)
        }
    },
    error => {
        if (axios.isCancel(error)) {
            console.log('Request canceled', error)
        } else {
            Message.error({ message: '服务异常，请稍后再试' })
            return Promise.reject(error)
        }
    }
)

export const AJAX = {
    get(url, param = {}, headers = {}) {
        return Request.get(url, {
            params: param,
            headers,
        })
    },
    post(url, param = null, headers = {}) {
        return Request.post(url, param, {
            headers,
        })
    },
    put(url, param = null, headers = {}) {
        return Request.put(url, param, {
            headers,
        })
    },
    file(url, param = null, headers = {}) {
        return Request.post(url, param, {
            headers: Object.assign(
                {
                    'Content-Type': 'multipart/form-data',
                },
                headers
            ),
        })
    },
    delete(url, param = null, headers = {}) {
        return Request.delete(url, {
            param,
            headers: Object.assign(
                {
                    'Content-Type': 'multipart/form-data',
                },
                headers
            ),
        })
    },
}
export default Request
